import json

def load_data_from_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return data
    except FileNotFoundError:
        print(f"错误: 文件 {file_path} 未找到。")
        return None
    except json.JSONDecodeError:
        print(f"错误: 文件 {file_path} 不是有效的 JSON 文件。")
        return None

def find_recent_decline(data, decline_days=3):
    stock_prices = {}
    all_dates = sorted({day["trandt"] for day in data}, reverse=True)

    # 获取最近指定天数的交易日期
    recent_dates = all_dates[:decline_days]

    # 组织数据，以股票代码为键，存储每个日期的收盘价
    for day in data:
        date = day["trandt"]
        if date not in recent_dates:
            continue
        for stock in day["data"]["diff"]:
            stock_code = stock["f12"]
            close_price = stock["f2"]

            if stock_code not in stock_prices:
                stock_prices[stock_code] = []

            stock_prices[stock_code].append((date, close_price))

    # 找出在最近指定天数内连续下跌的股票
    declining_stocks = []
    for stock_code, prices in stock_prices.items():
        # 检查是否连续下跌
        if len(prices) == decline_days and all(prices[i][1] > prices[i + 1][1] for i in range(len(prices) - 1)):
            declining_stocks.append({
                "stock_code": stock_code,
                "dates": [date for date, _ in prices],
                "prices": [price for _, price in prices]
            })

    return declining_stocks

def print_declining_stocks(declining_stocks, decline_days):
    print(f"连跌{decline_days}天的股票:")
    for decline in declining_stocks:
        print(f"股票代码: {decline['stock_code']}")
        print(f"日期: {decline['dates']}")
        print(f"价格: {decline['prices']}")
        print()

# 主程序执行
# file_path = '/Users/macbookair/workspace/pythonlearning/01test/tiantianjijin/all_processed_data.json'
file_path = 'D:\\PythonWorks\\pythonlearning\\01test\\tiantianjijin\\all_processed_data.json'
data = load_data_from_file(file_path)

if data:
    recent_three_day_declines = find_recent_decline(data, decline_days=3)
    recent_four_day_declines = find_recent_decline(data, decline_days=4)
    recent_five_day_declines = find_recent_decline(data, decline_days=5)

    print_declining_stocks(recent_three_day_declines, decline_days=3)
    print_declining_stocks(recent_four_day_declines, decline_days=4)
    print_declining_stocks(recent_five_day_declines, decline_days=5)
else:
    print("没有可处理的数据。")
